package com.hongxun.budget.ui.fragment.tk;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.IdRes;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.hongxun.budget.R;
import com.hongxun.budget.greendao.DMaterialBuyEntityDao;
import com.hongxun.budget.greendao.DMaterialOldEntityDao;
import com.hongxun.budget.greendao.DaoSession;
import com.hongxun.budget.ui.activity.tk.AddMaterialActivity;
import com.hongxun.budget.ui.fragment.BaseListFragment;
import com.hongxun.budget.utils.DBUtils;
import com.hongxun.budget.utils.GreenDaoManager;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.greenentity.tk.BMaterialEntity;
import com.hongxun.greenentity.tk.DMaterialBuyEntity;
import com.hongxun.greenentity.tk.DMaterialOldEntity;
import com.hongxun.greenentity.tk.DPointEntity;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 材料及附件
 */

public class MaterialFragment extends BaseListFragment implements RadioGroup.OnCheckedChangeListener {


    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;

    int select = 0;
    //新增设备数据
    List<DMaterialBuyEntity> addDatas = new ArrayList<>();
    SuperAdapter<DMaterialBuyEntity> addAdapter;
    List<DMaterialBuyEntity> addDeleteDatas = new ArrayList<>();
    //拆除设备数据
    List<DMaterialOldEntity> ccEntities = new ArrayList<>();
    SuperAdapter<DMaterialOldEntity> ccAdapter;
    List<DMaterialOldEntity> ccDeleteEntities = new ArrayList<>();
    //修理设备数据
    List<DMaterialOldEntity> xlEntities = new ArrayList<>();
    SuperAdapter<DMaterialOldEntity> xlAdapter;
    List<DMaterialOldEntity> xlDeleteEntities = new ArrayList<>();

    DMaterialBuyEntity dm;

    @Override
    protected int getMyListLayoutId() {
        return R.layout.fragment_material;
    }

    @Override
    public SuperAdapter getAdapter() {
        addAdapter = new SuperAdapter<DMaterialBuyEntity>(R.layout.content_fragment_material) {
            @Override
            public void bindView(ViewHolder viewHolder, final DMaterialBuyEntity d, final int i) {
                ((TextView) viewHolder.getView(R.id.device_type)).setText(d.getMBMidtype());
                ((TextView) viewHolder.getView(R.id.name)).setText(d.getMBName());
                ((TextView) viewHolder.getView(R.id.parameter)).setText(d.getMBParameter());
                ((TextView) viewHolder.getView(R.id.count)).setText(d.getMBCount() + "");
                viewHolder.getView(R.id.option_layout).setVisibility(View.GONE);
                ((TextView) viewHolder.getView(R.id.unit)).setText(d.getMBUnit());
                viewHolder.getView(R.id.change_old_device).setVisibility(View.VISIBLE);
                if (d.getMBSource().equals("系统")) {
                    viewHolder.getView(R.id.delete_old_device).setVisibility(View.GONE);
                    viewHolder.getView(R.id.edit_old_device).setVisibility(View.GONE);
                } else {
                    viewHolder.getView(R.id.delete_old_device).setVisibility(View.VISIBLE);
                    viewHolder.getView(R.id.edit_old_device).setVisibility(View.VISIBLE);
                    viewHolder.getView(R.id.delete_old_device).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {//删除
                            addDatas.remove(d);
                            addAdapter.notifyDataSetChanged();
                            addDeleteDatas.add(d);
                        }
                    });
                    viewHolder.getView(R.id.edit_old_device).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {//编辑
                            if (d.getMBName().startsWith("(利旧)")) {
                                T.showLong(context, "利旧材料不能编辑");
                                return;
                            }
                            DBUtils.editBuyMaterial(MaterialFragment.this, d, i, 2);
                        }
                    });
                    viewHolder.getView(R.id.change_old_device).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {//编辑
                            dm = d;
                            Intent intent = new Intent(context, AddMaterialActivity.class);
                            intent.putExtra("label", d.getMBBigtype());
                            intent.putExtra("change", true);
                            startActivityForResult(intent, 9);
                        }
                    });
                }
            }
        };
        ccAdapter = new SuperAdapter<DMaterialOldEntity>(R.layout.content_fragment_material) {
            @Override
            public void bindView(ViewHolder viewHolder, final DMaterialOldEntity d, final int i) {
                ((TextView) viewHolder.getView(R.id.device_type)).setText(d.getMBMidtype());
                ((TextView) viewHolder.getView(R.id.name)).setText(d.getMBName());
                ((TextView) viewHolder.getView(R.id.parameter)).setText(d.getMBParameter());
                ((TextView) viewHolder.getView(R.id.count)).setText(d.getMBCount() + "");
                ((TextView) viewHolder.getView(R.id.unit)).setText("(" + d.getMBUnit() + ")");
                viewHolder.getView(R.id.option_layout).setVisibility(View.VISIBLE);
                ((TextView) viewHolder.getView(R.id.option)).setText((d.getDROpinion().equals("10") ?
                        "利旧" : DBUtils.getBDataDictionaryEntity("opinion_type", d.getDROpinion()).getDValue()));
                viewHolder.getView(R.id.change_old_device).setVisibility(View.GONE);
                viewHolder.getView(R.id.delete_old_device).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//删除
                        if (d.getDROpinion().equals("10") && d.getMBCount() > Double.parseDouble(d.getDRWhere())) {
                            T.showLong(context, "该材料已被利旧，不能删除");
                            return;
                        }
                        ccEntities.remove(d);
                        ccAdapter.notifyDataSetChanged();
                        ccDeleteEntities.add(d);
                    }
                });
                viewHolder.getView(R.id.edit_old_device).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//编辑
                        if (d.getDROpinion().equals("10") && d.getMBCount() > Double.parseDouble(d.getDRWhere())) {
                            T.showLong(context, "该材料已被利旧，不能编辑");
                            return;
                        }
                        DBUtils.editOldMaterial(MaterialFragment.this, d, i, 3);
                    }
                });
            }
        };
        xlAdapter = new SuperAdapter<DMaterialOldEntity>(R.layout.content_fragment_material) {
            @Override
            public void bindView(ViewHolder viewHolder, final DMaterialOldEntity d, final int i) {
                ((TextView) viewHolder.getView(R.id.device_type)).setText(d.getMBMidtype());
                ((TextView) viewHolder.getView(R.id.name)).setText(d.getMBName());
                ((TextView) viewHolder.getView(R.id.parameter)).setText(d.getMBParameter());
                ((TextView) viewHolder.getView(R.id.count)).setText(d.getMBCount() + "");
                viewHolder.getView(R.id.option_layout).setVisibility(View.GONE);
                ((TextView) viewHolder.getView(R.id.unit)).setText("(" + d.getMBUnit() + ")");
                viewHolder.getView(R.id.change_old_device).setVisibility(View.GONE);
                viewHolder.getView(R.id.delete_old_device).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//删除
                        xlEntities.remove(d);
                        xlAdapter.notifyDataSetChanged();
                        xlDeleteEntities.add(d);
                    }
                });
                viewHolder.getView(R.id.edit_old_device).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//编辑
                        DBUtils.editOldMaterial(MaterialFragment.this, d, i, 3);
                    }
                });
            }
        };
        return select == 0 ? addAdapter : select == 1 ? ccAdapter : xlAdapter;
    }

    @OnClick(R.id.add_button)
    public void onViewClicked() {
        DBUtils.addMaterial(this, select == 0 ? "新增" : select == 1 ? "拆除" : "大修", 1);
    }

    @Override
    public void initView() {
        super.initView();
        initData();
        String process = (String) SPUtils.get(context, "process", "");
        select = process.equals("新增") ? 0 : process.equals("拆除") ? 1 : 2;
        set(select);
        radioGroup.check(select == 0 ? R.id.radioButton1 : select == 1 ? R.id.radioButton2 : R.id.radioButton3);
        radioGroup.setOnCheckedChangeListener(this);
    }

    private void initData() {
        addDatas.addAll(DBUtils.getDMaterialBuyEntities(context));
        addAdapter.setData(addDatas);
        addAdapter.setEmptyDataView(R.layout.view_empty);
        ccEntities.addAll(DBUtils.getDMaterialOldEntities(context, "拆除"));
        ccAdapter.setData(ccEntities);
        ccAdapter.setEmptyDataView(R.layout.view_empty);
        xlEntities.addAll(DBUtils.getDMaterialOldEntities(context, "修理"));
        xlAdapter.setData(xlEntities);
        xlAdapter.setEmptyDataView(R.layout.view_empty);
    }


    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
        switch (i) {
            case R.id.radioButton1:
                select = 0;
                break;
            case R.id.radioButton2:
                select = 1;
                break;
            case R.id.radioButton3:
                select = 2;
                break;
        }
        set(select);
    }

    private void set(int i) {
        switch (i) {
            case 0:
                list.setAdapter(addAdapter);
                addAdapter.notifyDataSetChanged();
                break;
            case 1:
                list.setAdapter(ccAdapter);
                ccAdapter.notifyDataSetChanged();
                break;
            case 2:
                list.setAdapter(xlAdapter);
                xlAdapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && data != null) {
            switch (requestCode) {
                case 1://添加材料
                    List<BMaterialEntity> bMaterialEntities = (List<BMaterialEntity>) data.getSerializableExtra("material");
//                    BMaterialEntity b = (BMaterialEntity) data.getSerializableExtra("material");
                    for (BMaterialEntity b : bMaterialEntities)
                        setD(b, -1);
                    break;
                case 2://编辑新材料
                    int index = data.getIntExtra("index", 0);
                    DMaterialBuyEntity d = (DMaterialBuyEntity) data.getSerializableExtra("material");
                    addDatas.remove(index);
                    addDatas.add(index, d);
                    addAdapter.notifyDataSetChanged();
                    break;
                case 3://编辑旧材料
                    int i = data.getIntExtra("index", 0);
                    DMaterialOldEntity dd = (DMaterialOldEntity) data.getSerializableExtra("material");
                    if (select == 1) {
                        ccEntities.remove(i);
                        ccEntities.add(i, dd);
                        ccAdapter.notifyDataSetChanged();
                    } else if (select == 2) {
                        xlEntities.remove(i);
                        xlEntities.add(i, dd);
                        xlAdapter.notifyDataSetChanged();
                    }
                    break;
                case 4:
                    DPointEntity dPointEntity = (DPointEntity) data.getSerializableExtra("point");
                    if (!dPointEntity.getPPName().equals((String) SPUtils.get(context, "point_name", ""))) {
                        T.showLong(context, "请复制相同点位的设备。");
                        return;
                    }
                    if (dPointEntity.getGuid().equals((String) SPUtils.get(context, "UUID", ""))) {
                        T.showLong(context, "请选择其他相同点位。");
                        return;
                    }
                    copyPoint(dPointEntity);
                    break;
                case 9:
                    int indexOf = addDatas.indexOf(dm);
                    addDatas.remove(indexOf);
                    List<BMaterialEntity> bMaterialEntities2 = (List<BMaterialEntity>) data.getSerializableExtra("material");
//                    BMaterialEntity b = (BMaterialEntity) data.getSerializableExtra("material");
                    for (BMaterialEntity b : bMaterialEntities2)
                        setD(b, indexOf);
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void copyPoint(DPointEntity d) {
        DaoSession session = GreenDaoManager.getInstance().getmDaoSession();
        List<DMaterialBuyEntity> list = session.getDMaterialBuyEntityDao().queryBuilder()
                .where(DMaterialBuyEntityDao.Properties.PGuid.eq((String) SPUtils.get(context, "project_guid", ""))
                        , DMaterialBuyEntityDao.Properties.PPGuid.eq(d.getGuid())
                        , DMaterialBuyEntityDao.Properties.MBSource.notEq("系统")
                        , DMaterialBuyEntityDao.Properties.MBDatastate.notEq("删除")).list();
        for (DMaterialBuyEntity buy : list) {
            if (buy.getMBName().startsWith("(利旧)")) {
                DMaterialOldEntity old = session.getDMaterialOldEntityDao().load(buy.getMMGuid());
                double v = Double.parseDouble(old.getDRWhere());
                if (buy.getMBCount() > v) {
                    T.showLong(context, "该点位使用的利旧材料数量为: " + buy.getMBCount() + " ，剩余数量为: " + v + "。数量不足，无法添加。");
                    return;
                }
            }
        }
        List<DMaterialOldEntity> list2 = session.getDMaterialOldEntityDao().queryBuilder()
                .where(DMaterialOldEntityDao.Properties.PGuid.eq((String) SPUtils.get(context, "project_guid", ""))
                        , DMaterialOldEntityDao.Properties.PPGuid.eq(d.getGuid())
                        , DMaterialOldEntityDao.Properties.MBDatastate.notEq("删除")
                        , DMaterialOldEntityDao.Properties.MBWork.eq("拆除")).list();
        List<DMaterialOldEntity> list3 = session.getDMaterialOldEntityDao().queryBuilder()
                .where(DMaterialOldEntityDao.Properties.PGuid.eq((String) SPUtils.get(context, "project_guid", ""))
                        , DMaterialOldEntityDao.Properties.PPGuid.eq(d.getGuid())
                        , DMaterialOldEntityDao.Properties.MBDatastate.notEq("删除")
                        , DMaterialOldEntityDao.Properties.MBWork.eq("修理")).list();
        for (DMaterialBuyEntity buy : list) {
            BMaterialEntity load = session.getBMaterialEntityDao().load(buy.getMMGuid());
            load.setmCount(buy.getMBCount());
            DMaterialBuyEntity dMaterialBuyEntity = DBUtils.addBuyMaterial(context, load);
            addDatas.add(dMaterialBuyEntity);
        }
        for (DMaterialOldEntity cc : list2) {
            BMaterialEntity load = session.getBMaterialEntityDao().load(cc.getMMGuid());
            load.setmCount(cc.getMBCount());
            DMaterialOldEntity dMaterialOldEntity = DBUtils.addOldMaterial(context, load, "拆除");
            ccEntities.add(dMaterialOldEntity);
        }
        for (DMaterialOldEntity xl : list3) {
            BMaterialEntity load = session.getBMaterialEntityDao().load(xl.getMMGuid());
            load.setmCount(xl.getMBCount());
            DMaterialOldEntity dMaterialOldEntity = DBUtils.addOldMaterial(context, load, "修理");
            xlEntities.add(dMaterialOldEntity);
        }
        if (select == 0) {
            addAdapter.notifyDataSetChanged();
        } else if (select == 1) {
            ccAdapter.notifyDataSetChanged();
        } else {
            xlAdapter.notifyDataSetChanged();
        }
    }

    private void setD(BMaterialEntity b, int i) {
        if (select == 0) {
            for (DMaterialBuyEntity d : addDatas) {
                if (d.getMMGuid().equals(b.getGuid()) && d.getMBName().startsWith("(利旧)")) {
                    T.showLong(context, "该利旧材料已选择，请重新选择");
                    return;
                }
            }
            if (i != -1) addDatas.add(i, DBUtils.addBuyMaterial(context, b));
            else
                addDatas.add(DBUtils.addBuyMaterial(context, b));
            addAdapter.notifyDataSetChanged();
        } else if (select == 1) {
            ccEntities.add(DBUtils.addOldMaterial(context, b, "拆除"));
            ccAdapter.notifyDataSetChanged();
        } else if (select == 2) {
            xlEntities.add(DBUtils.addOldMaterial(context, b, "修理"));
            xlAdapter.notifyDataSetChanged();
        }
    }

    public void insertDB() {
        for (DMaterialOldEntity d : ccEntities) {
            DBUtils.deleteCost(context, d.getGuid());
            DBUtils.addMaterialCost(context, d.getMMGuid(), d.getGuid(), d.getMBName(), 1, 3, 2, d.getMBCount());
        }
        for (DMaterialOldEntity d : ccDeleteEntities) {
            DBUtils.deleteCost(context, d.getGuid());
            d.setMBDatastate("删除");
        }
        GreenDaoManager.getInstance().getmDaoSession().getDMaterialOldEntityDao().insertOrReplaceInTx(ccEntities);
        GreenDaoManager.getInstance().getmDaoSession().getDMaterialOldEntityDao().updateInTx(ccDeleteEntities);

        for (DMaterialOldEntity d : xlEntities) {
            DBUtils.deleteCost(context, d.getGuid());
            DBUtils.addMaterialCost(context, d.getMMGuid(), d.getGuid(), d.getMBName(), 1, 3, 3, d.getMBCount());
        }
        for (DMaterialOldEntity d : xlDeleteEntities) {
            DBUtils.deleteCost(context, d.getGuid());
            d.setMBDatastate("删除");
        }
        GreenDaoManager.getInstance().getmDaoSession().getDMaterialOldEntityDao().insertOrReplaceInTx(xlEntities);
        GreenDaoManager.getInstance().getmDaoSession().getDMaterialOldEntityDao().updateInTx(xlDeleteEntities);

        DMaterialBuyEntity removeD = null;//记录系统自动生成的导线并在添加导线的时候移除。
        for (DMaterialBuyEntity d : addDatas) {
            DBUtils.deleteCost(context, d.getGuid());
            if (d.getMBDatastate().equals("系统")) {
                removeD = d;
            }
            if (d.getMBName().startsWith("(利旧)")) {
                DMaterialOldEntity load = GreenDaoManager.getInstance().getmDaoSession().getDMaterialOldEntityDao().load(d.getMMGuid());
                load.setDRWhere((load.getMBCount() - d.getMBCount()) + "");
                load.setMBDatastate("修改");
                GreenDaoManager.getInstance().getmDaoSession().getDMaterialOldEntityDao().update(load);
                DBUtils.addMaterialCost(context, load.getMMGuid(), d.getGuid(), d.getMBName(), 1, 4, 1, d.getMBCount());
            } else {
                DBUtils.addMaterialCost(context, d.getMMGuid(), d.getGuid(), d.getMBName(), 1, 4, 1, d.getMBCount());
            }
        }
        for (DMaterialBuyEntity d : addDeleteDatas) {
            DBUtils.deleteCost(context, d.getGuid());
            d.setMBDatastate("删除");
            if (d.getMBName().startsWith("(利旧)")) {//查询开始时是否添加过该利旧材料,如果添加后再删除则处理，否则不处理
                DMaterialBuyEntity entity = GreenDaoManager.getInstance().getmDaoSession().getDMaterialBuyEntityDao().load(d.getGuid());
                if (entity != null) {
                    DMaterialOldEntity load = GreenDaoManager.getInstance().getmDaoSession().getDMaterialOldEntityDao().load(d.getMMGuid());
                    load.setDRWhere((Double.parseDouble(load.getDRWhere()) + d.getMBCount()) + "");
                    load.setMBDatastate("修改");
                    GreenDaoManager.getInstance().getmDaoSession().getDMaterialOldEntityDao().update(load);
                }
            }
        }
        if (removeD != null)//删除系统生成的导线信息(有且只有一条)
            addDatas.remove(removeD);
        GreenDaoManager.getInstance().getmDaoSession().getDMaterialBuyEntityDao().insertOrReplaceInTx(addDatas);
        GreenDaoManager.getInstance().getmDaoSession().getDMaterialBuyEntityDao().updateInTx(addDeleteDatas);
    }

}
